#![allow(unused_imports,dead_code,unused_assignments)]
use axum::{
    extract::{Form, Query, Json, Multipart,DefaultBodyLimit},
    routing::{get,post},
    response::Response,
    body::{Body, Bytes},
    Router
};
use crate::domain::GoodsBean;
use crate::domain::GoodsQueryRequest;
use crate::serviceimpl::goods_service::select_goods_by_recommend as service_select_goods_by_recommend;
use crate::serviceimpl::recommend_service::add_recommend_type as service_add_recommend_type;
use crate::serviceimpl::recommend_service::remove_recommend_type as service_remove_recommend_type;
use crate::serviceimpl::goods_service::count_active_goodses_by_recommend_type_id as service_count_active_goodses_by_recommend_type_id;
use serde::{Deserialize};
use serde_json::{Value,Map};
use std::collections::HashMap;
use std::fs;
use std::sync::Mutex;
use tower_http::{trace::TraceLayer};


lazy_static! {
	static ref TEMP_GOODS_IMAGES:Mutex<HashMap<String,String>> = Mutex::new(HashMap::new());
}

pub fn store_goods_picture(key:String,photo:String) {
	TEMP_GOODS_IMAGES.lock().unwrap().insert(key,photo);
}

pub fn pick_goods_picture(key:String) ->String {
	let ret:Option<String> = TEMP_GOODS_IMAGES.lock().unwrap().get(&key).cloned();
	TEMP_GOODS_IMAGES.lock().unwrap().insert(key,"".to_string());
	if ret.is_none() {
		return "".to_string();
	}
	ret.as_ref().unwrap().to_string()
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GoodsRequest {
	pub id: Option<i64>,
	pub name: Option<String>,
	pub active: Option<bool>,
	pub price: Option<f64>,
	pub intro: Option<String>,
	pub stock: Option<i32>,
	pub goods_type_id: Option<i64>,
	pub is_scroll: Option<bool>,
	pub is_hot: Option<bool>,
	pub is_new: Option<bool>,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GoodsRecommendCustRequest {
	pub recommend_type_id: i64,
	pub page: i32,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IdsRequest {
	pub ids: String,
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RecommendCustRequest {
    pub goods_id: Option<i64>,
	pub recommend_type_id: Option<i64>,
}

pub fn admin_goods_cust_controller() -> Router {
	Router::new()
	.route("/goods_list", post(goods_list))
	.route("/addRecommendType", post(add_recommend_type))
	.route("/removeRecommendType", post(remove_recommend_type))
	.layer(DefaultBodyLimit::max(2*1024*1024))
	.layer(TraceLayer::new_for_http())
}

pub async fn goods_list(Form(goods_recommend_cust_request):Form<GoodsRecommendCustRequest>) ->String {
    let recommend_type_id:i64= goods_recommend_cust_request.recommend_type_id;
    let page:i32 = goods_recommend_cust_request.page;
	let goodses = service_select_goods_by_recommend(recommend_type_id,page).await;
	let totalCount:i32 = service_count_active_goodses_by_recommend_type_id(recommend_type_id).await.unwrap().count_num as i32;
    let totalPage:i32 = (totalCount as f64/8.0).ceil() as i32;
	match goodses {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(goodses) => {
			let json = serde_json::to_string_pretty(&goodses).unwrap();

			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert("pageNumber".to_string(), Value::from(page));
			map.insert("pageSize".to_string(), Value::from(8));
			map.insert("totalCount".to_string(), Value::from(totalCount));
			map.insert("totalPage".to_string(), Value::from(totalPage));
			map.insert(
				"rows".to_string(),
				serde_json::from_str(&json).unwrap(),
			);

			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn add_recommend_type(Json(recommend_cust_request):Json<RecommendCustRequest>) ->String {
    let goods_id = recommend_cust_request.goods_id.unwrap_or_default();
	let recommend_type_id = recommend_cust_request.recommend_type_id.unwrap_or_default();
	let _result = service_add_recommend_type(goods_id,recommend_type_id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);

			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}

pub async fn  remove_recommend_type(Json(recommend_cust_request):Json<RecommendCustRequest>) ->String {
    let goods_id = recommend_cust_request.goods_id.unwrap_or_default();
	let recommend_type_id = recommend_cust_request.recommend_type_id.unwrap_or_default();
	let _result = service_remove_recommend_type(goods_id,recommend_type_id).await;
	match _result {
		Err(_) => {
			r#"{  "rows": null,  "success": true}"#.to_string()
		},
		Ok(_result) => {
			let mut map = Map::new();
			map.insert("success".to_string(), Value::from(true));
			map.insert(
				"rows".to_string(),
				Value::from(""),
			);

			let resultjson = serde_json::to_string_pretty(&map).unwrap();
			return resultjson;
		}
	}
}
